(function($) {
	var methods = {
			"init": function(options){
				$.extend( $.mtgpi.global, options );
				return this.each(function(){
					$.mtgpi.create();
				});
			}
		};

	$.mtgpi = {};
	
	$.mtgpi.global = {
		//global variables
		"containingDiv": "mtgBody",
		"mtgID": null,
		"mtgType": null,
		"mtgStarter": null,
		"attendantMode": null,
		"aliases": [],
		"users": [],
		"admins": [],
		"signedIn": []
	};
	
	$.fn.marcMeetingAttendant = function( method ) {	    
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.dialogPrompt' );
		}
	};
	
	//PRIMARY PROGRAM LOGIC FUNCTION
	$.mtgpi.create = function()
	{
		//first, fire off a call to gather info on any active meetings
		$.ajax({ 
	  	  	url:"/marc/MeetingSigninService",
	  	  	data:{"RequestType":"CheckForOpenMeetings"},
			type:'POST',
			dataType:"json",
			success: function(html)
			{
				//if data is returned, store it for use below 
				var _meetingIDs = html['MeetingIDs'];
				var _meetingTypes = html['MeetingTypes'];
				var _meetingStarters = html['MeetingStarters'];
				var _meetingAttendant = html['MeetingAttendant'];
				
				//if the number of active meetings is 1, save it's values and return
				if(_meetingIDs.length  == 1)
				{
					$.mtgpi.global.mtgID = _meetingIDs[0];
					$.mtgpi.global.mtgType = _meetingTypes[0];
					$.mtgpi.global.mtgStarter = _meetingStarters[0];
					$.mtgpi.global.attendantMode = _meetingAttendant[0];
					
					//Load sign in page
					$.mtgpi.loadAttendedPlugin();
				}
				
				//if more than one meeting is returned, ask the user which they want to join
				else if(_meetingIDs.length > 1)
				{
					//create a dropdown to pick which meeting to join
					var _options = $('<select>').attr('id','activeMeetings');
					
					//for each meeting type, create an option in the dropdown
					for(var i=0; i<_meetingTypes.length; i++)
					{
						var thisType = _meetingTypes[i];
						_options.append(
								$('<option>')
									.attr({
										'id':i,
										'value':thisType
									})
									.text(thisType + "	(#" + _meetingIDs[i] + ")")
						);
					};
					
					//create a div for the multiple meeting dialog
					$.mtgpi.global.containingDiv.append(
						$('<div>')
							.attr('id','multipleMtgDialog')
							.append($('<center>')
								.append($('<img>')
									.attr('src','img/alert.png')
									.css('height','100px'))
								.append($('<br>')).append($('<br>'))
								.append("There are currently " + _meetingIDs.length + " meetings active. <br>Which would you like to join?")
								.append($('<form>').attr('id','pickAMeetingForm').append(_options).append($('<input>').attr({'type':'submit', 'value':'Join!'})))
							)
					);
					
					//when the user picks a meeting...
					$('#pickAMeetingForm').submit(function(e)
					{
						//stop the page from reloading
						e.preventDefault();
						
						//apply the chosen values to the global variables
						$.mtgpi.global.mtgID = _meetingIDs[$('#activeMeetings option:selected').attr('id')];
						$.mtgpi.global.mtgType = _meetingTypes[$('#activeMeetings option:selected').val()];
						$.mtgpi.global.mtgStarter = _meetingStarters[$('#activeMeetings option:selected').attr('id')];
						$.mtgpi.global.attendantMode = _meetingAttendant[$('#activeMeetings option:selected').attr('id')];
						
						//get rid of the dialog
						$('#multipleMtgDialog').dialog('close');
						$('#multipleMtgDialog').remove();
						
						$.mtgpi.loadAttendedPlugin();
					});
					
					//actually display the dialog, and tell it where to go
					$('#multipleMtgDialog').dialog();
					$('#multipleMtgDialog').dialog( "option", "width", '75%' );
					$('#multipleMtgDialog').dialog( "option", "position", 'center' );
				}
				//otherwise, there aren't any active meetings; return to sender
				else
				{
					alert('There are no active meetings. Please return to the admin page to start one.');
					window.location = "index.jsp";
				}
				
				//last, get the list of all available aliases
				$.mtgpi.gatherAliasInfo();
			},
			error: function(html)
			{
				alert("An error occured while gathering Active Meeting data." +
						"\nPlease refresh your browser and try again." +
						"\n\nIf problem persists please contact BigHelp Ministries.");
			}
		}); //Closes AJAX
	};
	
	$.mtgpi.gatherAliasInfo = function()
	{
		var _mtgID = $.mtgpi.global.mtgID;
		//ajax call to get list of active ID - user pairs
		$.ajax({ 
	  	  	url:"/marc/MeetingSigninService",
	  	  	data:
	  	  	{	"RequestType":"getActiveList", 
	  	  		"MeetingID": _mtgID
	  	  	},
			type:'POST',
			dataType:"json",
			success: function(html)
			{
				var _aliases = html['ActiveAliases'];
				var _users = html['ActiveUsers'];
				var _admins = html['ActiveAdmins'];
				var _signedIn = html['inUsers'];
				
				var _fullList = _aliases.concat(_users);
				
				$.mtgpi.global.aliases = _fullList;
				$.mtgpi.global.users = _users;
				$.mtgpi.global.admins = _admins;
				$.mtgpi.global.signedIn = _signedIn;
			},
	  	  	error: function(html)
			{
				alert("An error occured while gathering Active User data." +
						"\nPlease refresh your browser and try again." +
						"\n\nIf problem persists please contact BigHelp Ministries.");
			}
		}); //Closes AJAX
	};
	
	$.mtgpi.loadAttendedPlugin = function()
	{
		var _appBody = $('#'+$.mtgpi.global.containingDiv);
		
		_appBody.append(
			$('<div>')
				.attr({
					'id':'controlColumn'
				})
				.css({
				    'border-right':'1px solid #333333',
				    'top':'10px',
					'left':'5px',
					'height':'98%',
					'width':'24%',
					'position':'absolute'
				})
				.append(
					$('<center>')
						.append(
							$('<img>')
								.attr({
									'src':'img/marc_logo.jpg',
									'height':'100'
								})
						).append($('<br/>'))
						.append(
							$('<a>')
								.attr({
									'href':'#'
								})
								.append(
									$('<img>')
										.attr({
											'src':'img/search-by-name.jpg',
											'id':'peopleSearch'
										})
										.css({
											'margin-top':'30px',
											'margin-right':'50%',
											'width':'85%',
											'position':'relative'
										})
								)
						).append($('<br/>'))
						.append(
								$('<a>')
									.attr({
										'href':'#'
									})
									.append(
										$('<img>')
											.attr({
												'src':'img/admin.png',
												'id':'adminMenu'
											})
											.css({
												'margin-top':'10px',
												'margin-right':'50%',
												'width':'85%',
												'position':'relative'
											})
									)
							).append($('<br/>'))
							.append(
									$('<a>')
										.attr({
											'href':'#'
										})
										.append(
											$('<img>')
												.attr({
													'src':'img/close.jpg',
													'id':'closeMeeting'
												})
												.css({
													'margin-top':'10px',
													'margin-right':'50%',
													'width':'85%',
													'position':'relative'
												})
										)
								)
					)
			)
			.append(
				$('<div>')
					.attr({
						'id':'memberColumn'
					})
					.css({
						'border':'2px solid red',
					    'top':'10px',
						'left':'25%',
						'height':'98%',
						'width':'50%',
						'position':'absolute'
					})
					.append(
						$('<center>')
							.append(
								$('<form>')
									.attr('id','aliasEntryForm')
									.append($('<input>')
										.attr({
											'id':'aliasEntryBox',
											'type':'text'
										})
									)
									.css({
											'top':'15px',
											'position':'relative',
											'size':'50'
										}).append($('<br/>'))
							).append($('<br/>'))
							.append(
								$('<img>')
									.attr({
										'id':'logoImg',
										'src':'img/logo.png'
									})
									.css({
										'top':'100px',
										'position':'relative'
									})
							)
					)
			)
			.append(
				$('<div>')
					.attr({
						'id':'meetingColumn'
					})
					.css({
						'border-left':'1px solid #333333',
					    'top':'10px',
						'right':'5px',
						'height':'98%',
						'width':'24%',
						'position':'absolute'
					})
			);
			$('#aliasEntryBox').focus();
			$('#peopleSearch').click(function()
			{
				alert("People Search Clicked!");
				
				var _masterList = $.mtgpi.global.users;
				
				//create a dropdown to pick which meeting to join
				var _memberList = $('<select>').attr('id','activeMembers');
				
				//for each meeting type, create an option in the dropdown
				for(var i=0; i<_masterList.length; i++)
				{
					var _thisMember = _masterList[i];
					var _nameString = _thisMember['LName'] + ", " + _thisMember['Pref_Name'] + " (" + _thisMember['UserID'] + ")";
					
					_memberList.append(
							$('<option>')
								.attr({
									'id':_thisMember['UserID'],
									'value':_nameString
								})
								.text(_nameString)
					);
				};
				
				$('#aliasEntryBox').focus();
			});
			$('#adminMenu').click(function()
			{
				alert("Admin Menu Clicked!");
				$('#aliasEntryBox').focus();
			});
			$('#closeMeeting').click(function()
			{
				alert("End Meeting Clicked!");
				$('#aliasEntryBox').focus();
			});
			
			
			$('#aliasEntryForm').submit(function(e)
			{
				//Stop the form from refreshing the page
				e.preventDefault();
				
				//Get the list of active users from global, and the entered alias from the textbox
				var _enteredAlias = $('#aliasEntryBox').val();
				
				//send the data down to the SignInUser function for parsing
				$.mtgpi.SignInUser(_enteredAlias, $('#memberColumn'));
			});
			
	};
	
	$.mtgpi.SignInUser = function(_enteredAlias, _targetDiv)
	{
		var _user = $.mtgpi.parseAlias(_enteredAlias);
		if(_user == -1) //if user not found
		{
			//display user not found dialog
			//create a dialog div to ask the user what they want to do with the ID
			$('#globalSettings').append(
					$('<div>')
						.attr({'id':'aliasNotFoundDialog', 'title':'Alias Not Found'})
						.append($('<center>').append($('<img>').attr('src','img/doNotEnter.png').css({'height':'200px'}))
						.append($('<br>'))
						.append($('<h2>').append("Sorry, that entry did not match any alias on record.")))
				);
				
			//create a list of users in case they decide to append the new alias to an existing user
			var _options = [];
			var _activeUsers = $.mtgpi.global.users;
			$.each(_activeUsers, function(index, _currUser) 
			{ 
				_options.push($('<option>').attr('value',_currUser['UserID']).text(_currUser['LName'] + ', ' + _currUser['Pref_Name']));
			});

			$('#aliasNotFoundDialog').dialog({
					buttons: {
						'New Alias (existing user)': function()
						{
							$('h2').remove();
							$('#aliasNotFoundDialog')
								.append($('<h2>')
									.append($('<form>').attr({'id':'associateAliasForm'})
										.append("Who do you want to associate this alias with?<br>")
										.append(
											$('<select>')
												.attr('id','userToAssociateWith')
												.append(_options)
										)
										.append($('<br>'))
										.append($('<input>').attr({'type':'submit','value':'Sign In'}))
									)
								);
							$('#associateAliasForm').submit(function(e)
							{
								e.preventDefault();
								
								var _requestedUser = $('#userToAssociateWith option:selected').attr('id');
								
								$('h2').remove();
								$('#aliasNotFoundDialog')
									.append($('<h2>')
										.append("This action requires administrator approval.<br>")
										.append($('<form>')
											.attr({'id':'approvingAdmin'})
											.append($('<input>')
												.attr({'type':'text','id':'approvingAdminID'})
												.focus()
											)
										)
									);
								$('#approvingAdmin').submit(function(e){
									e.preventDefault();
									
									var _enteredAdmin = $('#approvingAdminID').val();
									var _parsedAdmin = $.mtgpi.parseAlias(_enteredAdmin);
									if(_parsedAdmin['IsAdmin'])
									{
										//TODO add list of other possible alias types
										_aliasType = "RFID";
										_authorizedAdmin = true;

										//AJAX to add alias to user
										$.ajax({ 
									  	  	url:"/marc/UserInfoService",
									  	  	data:
									  	  	{
									  	  		"RequestType":"AssociateNewAlias",
									  	  		"UserID":_requestedUser,
									  	  		"Alias":_enteredAlias,
									  	  		"AliasType":_aliasType
									  	  	},
											type:'POST',
											dataType:"json",
											success: function(html)
											{
												if(html["result"] == 1)
												{
													$('#aliasNotFoundDialog').dialog("close").remove();
													$('#aliasEntryBox').val('').focus();
												}
												else
												{
													alert("An error occurred while associating the new alias. Please try again later.");
												}
											},
											error: function(html)
											{
												alert("An error occured while associating the new alias." +
														"\nPlease refresh your browser and try again." +
														"\n\nIf problem persists please contact BigHelp Ministries.");
											}
										}); //Closes AJAX
									}
									else
									{
										alert("You are not an authorized admin!");
										$('#aliasNotFoundDialog').dialog("close").remove();
										$('#aliasEntryBox').val('').focus();
									}
								});
							});
						}, 
						'I\'m a visitor': function()
						{
							$('h2').remove();
							$('#aliasNotFoundDialog')
							.append(
								$('<h2>')
								.append($('<center>')
									.append("Great, welcome!! <br>Who are you with?<br>")
									.append(
										$('<select>')
											.attr('id','userToAssociateWith')
											.append(_options)
									)
								)
							);
						},
						'Cancel': function()
						{
							$('#aliasNotFoundDialog').dialog("close").remove();
							$('#aliasEntryBox').val('').focus();
						}
					}
				});
				$('#aliasNotFoundDialog').dialog( "option", "width", '75%' );
				$('#aliasNotFoundDialog').dialog( "option", "position", 'center' );
				$('#aliasEntryBox').val('').focus();
			//if(_authenticatingUser['IsAdmin']){AJAX - associate new alias} else{alert("You are not an authorized admin!");}
		}
		else //else if user found
		{
			if(_user['IsAlreadyIn']) //if user already in
			{
				if(_user['IsAdmin'])//admin double-tap
				{
					_targetDiv.append(
						$('<div>')
							.attr({'id':'adminMenuDialog', 'title':'Admin Menu'})
							.append(
									$('<img>')
										.attr('src','img/admin.png')
										.css({
											'height':'50px',
											'margin-top':'10px',
											'margin-left':'10px'
										})
								).append($('<br>'))
								//TODO admin menu
						);
						$('#adminMenuDialog').dialog({
							buttons: {
								'Cancel': function()
								{
									$('#adminMenuDialog').dialog('close');
									$('#adminMenuDialog').remove();
									
									//put the cursor back in the textbox
									$('#aliasEntryBox').val('').focus();
									return;
								}
							},
							options:{
								"width": '75%',
								"height": '75%',
								"position": 'center'
							}
						});
					return;
				}
				else //student Double-tap
				{
					_targetDiv.append(
							$('<div>')
								.attr({'id':'2ndSwipeBox', 'title':'Double-tap Menu'})
								.append($('<center>').append($('<img>').attr('src', _user['Picture']).css({'height':'150px'})))
						);
						//turn the div into a dialog, and add some cool graphics on close
						$('#2ndSwipeBox').dialog({hide: "explode"});
						
						
						//put the cursor back in the textbox
						$('#aliasEntryBox').val('').focus();
						return;
				}
			}
			else //sign the user in
			{
				//create a welcome dialog div
				_targetDiv.append(
					$('<div>')
						.attr('id','welcomeBox')
						.append($('<h2>').append("Welcome " + _user['Pref_Name'] + "!\n"))
						.append($('<center>').append($('<img>').attr('src', _user['Picture']).css({'height':'150px'})))
				);
				
				//turn the div into a dialog, and add some cool graphics on close
				$('#welcomeBox').dialog({hide: "explode"});
				
				//AJAX - sign in user
				$.ajax({ 
			  	  	url:"/marc/MeetingSigninService",
			  	  	data:
			  	  	{
			  	  		"RequestType":"signUserIn",
			  	  		"MeetingID":$.mtgpi.global.mtgID,
			  	  		"AliasUsed":_enteredAlias,
			  	  		"UserID":_user['UserID']
			  	  	},
					type:'POST',
					dataType:"json",
					success: function(html)
					{
						//dump out the currently signed in list
						$.mtgpi.global.signedIn = [];
						
						//grab the list of currently signed in users that was passed back
						$.mtgpi.global.signedIn = html['inUsers'];
						
						//automatically close the dialog after a short time
						setTimeout(function(){$('#welcomeBox').dialog("close").remove();},1000);
						
						//put the cursor back in the textbox
						$('#aliasEntryBox').val('').focus();
					},
					error: function(html)
					{
						alert("An error occured while signing in that user." +
								"\nPlease refresh your browser and try again." +
								"\n\nIf problem persists please contact BigHelp Ministries.");
					}
				}); //Closes AJAX
				
			}
		}
	};
	
	$.mtgpi.parseAlias = function(_enteredAlias)
	{
		var _aliasList = $.mtgpi.global.aliases;
		var _inList = $.mtgpi.global.signedIn;
		var _adminList = $.mtgpi.global.admins;
		var _userFound = false;
		var _isAdmin = false;
		var _alreadySignedIn = false;
		var _userDetails = [];
		
		$.each(_aliasList, function(index, _currAlias)
		{
			if(_currAlias['Alias'] == _enteredAlias)
			{
				_userFound = true;
				
				$.each(_inList, function(index, _currInUser)
				{
					if(_currInUser == _currAlias['UserID'])
					{
						_alreadySignedIn = true;
					}
				});
				$.each(_adminList, function(index, _currAdmin)
				{
					if(_currAdmin['UserID'] == _currAlias['UserID'])
					{
						_isAdmin = true;
					}
				});
				
				_userDetails['UserID'] = _currAlias['UserID'];
				_userDetails['Pref_Name'] = _currAlias['Pref_Name'];
				_userDetails['LName'] = _currAlias['LName'];
				_userDetails['Picture'] = _currAlias['Picture'];
				_userDetails['IsAlreadyIn'] = _alreadySignedIn;
				_userDetails['IsAdmin'] = _isAdmin;
			}
		});
		
		if(_userFound)
		{
			return _userDetails;
		}
		else
		{
			return -1;
		}
	};
	
	$.mtgpi.blah = function()
	{

	};
	
		
})(jQuery);